<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/7/6 下午1:56
 * +-------------------------------------------------------------
 */

namespace app\admin\controller;

use app\admin\model\SysConfig;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;

/**
 * @ControllerAnnotation (title="系统配置")
 */
class Config extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SysConfig();
    }

    public function info(): Json
    {
        $group  = $this->model->group('group')->column('group');
        $info = [];
        foreach($group as $item){
            $info[$item] = $this->model->where('group',$item)->field('name,value')->select()->toArray();
        }
        return $this->successJson($info);
    }
    /**
     * 格式化数据
     * @param $data
     * @return array
     */
    private function formatInfo($data): array
    {
        $newData = [];
        foreach($data as $item){
            $newData[$item['name']] = $item['value'];
        }
        return $newData;
    }

    /**
     * @NodeAnnotation (title="保存配置")
     * @param Request $request
     * @return Json
     */
    public function save(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $post = $request->post();
        try {
            $this->model->transaction(function() use ($post){
                foreach( $post as $key => $item){
                    $group = $key;
                    $item  = json_decode($item,true);
                    if($item) $this->configSave($item,$group);
                }
            });
        }catch( \Exception $e){
            return $this->errorJson("保存失败:".$e->getMessage());
        }
        return $this->successJson('保存成功！');
    }


    /**
     * @param $item
     * @param $group
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function configSave($item,$group): void
    {
        foreach($item as  $name => $value){
            $row = $this->model->where('group',$group)->where('name',$name)->find();
            if(!$row) {
               $this->model->create(['group'=>$group,'name'=>$name,'value'=>$value]);
            }else{
                $row->save(['value'=>$value]);
            }
        }
    }

}